<template>
  <div class="trendpad">
    <!-- -->
    <div id="trendpad-echarts" class="content"></div>
    <div class="footer">
      <!-- <div style="margin-left: 10px;color:#ffffff;">
        Page:
        <el-button @click="clickPrevious">&lt;</el-button>
        <el-button @click="clickNext">&gt;</el-button>
      </div>-->
      <!-- <div class="footer-item">
                Axis:
                <el-select v-model="form.region" placeholder="Please Select">
                    <el-option label="1 week" value="1"></el-option>
                    <el-option label="2 week" value="2"></el-option>
                </el-select>
      </div>-->
      <div class="footer-item" style="margin-left: 5rem;">
        Start:
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="Please enter"
          :disabled-date="disabledStartDate"
          :disabled="form.endTime && form.startTime > form.endTime"
          @change="changeStartTime"
        ></el-date-picker>
      </div>
      <div class="footer-item" style="margin-left: -24rem;">
        End:
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="Please enter"
          :disabled="form.startTime && form.endTime < form.startTime"
          @change="changeEndTime"
        ></el-date-picker>
      </div>
      <!-- <div class="footer-item">
        Interval:
        <el-select v-model="form.interval" placeholder="Please Select" @change="changeInterval">
          <el-option label="8 hours" value="0"></el-option>
          <el-option label="1 day" value="1"></el-option>
          <el-option label="7 days" value="2"></el-option>
          <el-option label="14 days" value="3"></el-option>
          <el-option label="30 days " value="4"></el-option>
          <el-option label="60 days" value="5"></el-option>
        </el-select>
      </div> -->
      <!-- <div class="footer-item">
                Update(s):
                <el-input
                    v-model="form.update"
                    placeholder="Please enter"
                ></el-input>
      </div>-->
      <div class="footer-item" style="display: flex; margin-left: -13rem;">
        <el-button type="primary" @click="exportpointCheck" :loading="exportLoading"
          style="width: 5rem;">Export</el-button>
        <el-button type="primary" @click="clickCheck">Search</el-button>
      </div>
    </div>
    <div class="export_daochu" v-if="exportdaochu == true" v-loading="loading" element-loading-text="Export is Loading">
      Export is loading</div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  getTrendByTagType,
  getTrendByTagName,
  getTrendOnlyByTagName,
  byTagName,
  byTagType
} from "@/api/index";
import { exportFile } from "@/utils/common";
// TODO使用mqtt 进行优化
// import socket from "@/utils/websocket";
export default {
  name: "trendPad",

  data() {
    return {
      exportdaochu: false,
      loading: false,
      form: {
        region: "",
        startTime: "",
        // endTime: new Date(),
        endTime: this.convertBeijingToCalgary(new Date()),
        interval: "3",
        update: ""
      },
      mychart: "",
      wellId: "8cf568aa-2a22-11ef-842d-6045bd5ed560",
      splitTimes: [],
      option: {
        title: [
          {
            x: "left",
            textStyle: {
              color: "rgba(219, 230, 255, 1)",
              fontSize: 16,
              fontWeight: "normal"
            },
            top: "2%",
            left: 10
          },
          {
            x: "left",
            textStyle: {
              color: "rgba(219, 0, 255, 1)",
              fontSize: 16,
              fontWeight: "normal"
            },
            top: "47%",
            left: 10
          }
        ],
        dataZoom: [
          {
            type: "inside",
            show: true,
            realtime: true,
            start: 0,
            end: 100,
            zoomLock: true,
            xAxisIndex: [0, 1]
          },
          {
            type: "slider",
            realtime: true,
            start: 0,
            end: 100,
            textStyle: {
              color: "white"
            },
            bottom: "2%",
            borderColor: "#43485E",
            dataBackground: {
              areaStyle: {
                color: "white"
              }
            }
          }
        ],
        backgroundColor: "#1B232E",
        tooltip: {
          show: true,
          trigger: "axis",
          axisPointer: {
            animation: false
          },
          formatter: function (params) {
            let showHtml = '';
            // 获取 x 轴的值
            let xAxisValue = params[0].axisValueLabel;
            // 显示 x 轴的值
            showHtml += `${xAxisValue}<br/>`;
            for (let i = 0; i < params.length; i++) {
              let value = params[i].value;
              let seriesName = params[i].seriesName;
              // 检查值是否为 NaN
              if (isNaN(value)) {
                // 如果是 NaN，使用红色字体显示
                showHtml += `${params[i].marker}<span style="color:red;">${seriesName}: NaN</span><br/>`;
              } else {
                // 如果不是 NaN，正常显示
                showHtml += `${params[i].marker}${seriesName}: ${value}<br/>`;
              }
            }
            return showHtml;
          },
          textStyle: {
            color: "rgba(255, 255, 255, 1)",
            align: "left"
          },
          backgroundColor: "rgba(0,0,0,0.8)",
          borderColor: "rgba(219, 230, 255, 0.8)"
        },
        axisPointer: {
          link: {
            xAxisIndex: "all"
          }
        },
        color: [
          "rgba(251, 210, 0, 1)",
          "rgba(250, 109, 62, 1)",
          "rgba(240, 244, 255, 1)"
        ],
        legend: [
          {
            data: ["WHT(°C)"],
            x: "left",
            textStyle: {
              color: "white",
              fontSize: 14
            },
            top: "2.5%",
            right: 30,
            left: 30,
            itemWidth: 20,
            itemHeight: 10,
            itemGap: 20
          }
        ],
        grid: [
          {
            // width: "1560px",
            // width: "96.4%",
            left: "20px",
            right: "40px",
            top: "10%",
            height: "80%",
            containLabel: true
          }
        ],
        xAxis: [
          {
            type: "category",
            boundaryGap: ["20%", "20%"],
            axisLabel: {
              formatter: function (value) {
                let res = ""; // 拼接加\n返回的类目项
                let maxLength = 10; // 每项显示文字个数  数字设置几，就一行显示几个文字
                let valLength = value.length; // X轴上的文字个数
                let rowN = Math.ceil(valLength / maxLength); // 需要换行的行数
                // 换行的行数大于1,
                if (rowN > 1) {
                  for (let i = 0; i < rowN; i++) {
                    let temp = ""; //每次截取的字符串
                    let start = i * maxLength; //开始截取的位置
                    let end = start + maxLength; //结束截取的位置
                    temp = value.substring(start, end) + "\n";
                    res += temp; //拼接字符串
                  }
                  return res;
                } else {
                  return value;
                }
              },
              color: "#A9AEB2",
              fontSize: 12,
              interval: 0, // 设置为0以显示所有标签
              showMaxLabel: true, // 确保显示最大值标签
              showMinLabel: true // 确保显示最小值标签
            },
            show: true,
            axisTick: {
              show: true
            },
            axisLine: {
              onZero: true,
              lineStyle: {
                color: "#515773"
              }
            },
            data: [
              "07/24 00:00",
              "07/24 01:00",
              "07/24 02:00",
              "07/24 03:00",
              "07/24 04:00",
              "07/24 05:00",
              "07/24 06:00",
              "07/24 07:00",
              "07/24 08:00",
              "07/24 09:00"
            ]
          }
        ],
        yAxis: [
          {
            type: "value",
            // max: 2000,
            // min: -200,
            // splitNumber: 11,
            axisLabel: {
              color: "#A9AEB2",
              fontSize: 12
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false,
              lineStyle: {
                color: "#515773"
              }
            },
            nameTextStyle: {
              color: "#A9AEB2",
              fontSize: "12"
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: ["#43485E"],
                width: 1,
                type: "solid"
              }
            }
          }
        ],
        series: [
          {
            name: "WHT(°C)",
            type: "line",
            emphasis: {
              focus: "series"
            },
            data: [100, 94, 83, 90, 88, 83, 90, 80, 88, 86],
            label: {
              show: false,
              color: "white"
            },
            lineStyle: {
              normal: {
                width: 1,
                color: "#177fe0"
              },

              // 鼠标悬停时的线条样式
              emphasis: {
                color: "#177fe0", // 高亮时线条颜色
                width: 2 // 高亮时线条宽度
              }
            },
            itemStyle: {
              color: "#177fe0"
            },
            symbol: "none"
          }
        ]
      },
      xData: [],
      xValue: [],
      exportLoading: false,
      xInterval: ""
    };
  },
  props: {
    type: {
      type: String,
      default: "curr"
    },
    tageName: {
      type: String,
      default: ""
    },
    tagName: {
      type: String,
      default: ""
    },
    unit: {
      type: String,
      default: ""
    },
    tagType: {
      type: Number,
      default: 6
    },
    keyType: {
      type: String,
      default: "2"
    }
  },
  created() {
    console.log(this.tagName, 'ooooo')
    let endTime = "";
    if (this.isDateObject(this.form.endTime)) {
      endTime = this.formatDate(this.form.endTime);
    } else {
      endTime = this.form.endTime;
    }
    this.calculateTime(endTime, "day14", "0");
    // const data = [];
    // for (var i = 0; i < 20000; i++) {
    //     data.push(Math.floor(Math.random() * 101));
    // }
    // console.log(data, "datadata");
    // const data2 = [];
    // for (var i = 0; i < 20000; i++) {
    //     data2.push(i + "");
    // }
    // console.log(data2, "datadata");
  },
  mounted() {
    // this.getESPTrend_WHT();
    this.getEachartsValue();
    window.addEventListener("resize", this.handleChartResize);
  },
  // beforeDestroy() {
  //   window.removeEventListener("resize", this.handleChartResize);
  // },

  methods: {
    handleChartResize() {
      if (!this.myChart) {
        return;
      }
      this.myChart.resize();
    },
    // 初始化图标
    init() {
      console.log(this.option, "option");
      // this.$nextTick(() => {
      var chartDom = document.getElementById("trendpad-echarts");
      this.myChart = echarts.init(chartDom);
      this.option && this.myChart.setOption(this.option);
      // });
      // var chartDom = document.getElementById("trendpad-echarts");
      // this.myChart = echarts.init(chartDom);
      // this.option && this.myChart.setOption(this.option);
    },
    disabledStartDate(time) {
      if (this.form.endTime) {
        return time.getTime() > new Date(this.form.endTime).getTime();
      }
      return false;
    },
    changeStartTime(item) {
      const date = new Date(item);
      const year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hours = date.getHours();
      let minutes = date.getMinutes();
      let seconds = date.getSeconds();
      month = month < 10? '0' + month : month;
      day = day < 10? '0' + day : day;
      hours = hours < 10? '0' + hours : hours;
      minutes = minutes < 10? '0' + minutes : minutes;
      seconds = seconds < 10? '0' + seconds : seconds;
      this.form.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      if (this.form.endTime && this.form.startTime > this.form.endTime) {
        this.form.startTime = this.form.endTime;
      }
    },
    changeEndTime(value) {
      if (this.form.startTime && this.form.endTime < this.form.startTime) {
        this.form.endTime = this.form.startTime;
      }
        //  let endTime = "";
      // if (this.isDateObject(this.form.endTime)) {
      //   endTime = this.formatDate(this.form.endTime);
      // } else {
      //   endTime = this.form.endTime;
      // }
      // if (this.form.interval == "0") {
      //   // 8小时
      //   this.calculateTime(endTime, "hour", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else if (this.form.interval == "1") {
      //   // 1天
      //   this.calculateTime(endTime, "day", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else if (this.form.interval == "2") {
      //   // 7天
      //   this.calculateTime(endTime, "day7", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else if (this.form.interval == "3") {
      //   // 14天
      //   this.calculateTime(endTime, "day14", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else if (this.form.interval == "4") {
      //   // 30天
      //   this.calculateTime(endTime, "day30", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // } else {
      //   // 60天
      //   this.calculateTime(endTime, "day60", "0");
      //   console.log(this.form.startTime, "this.form.startTime");
      // }
    },
    changeInterval(value) {
      console.log(value, "interval");
      console.log(this.form.interval, "interval");
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      // 刚进页面 starttime为空或者null，endtime有值 选择interval时
      if (this.form.startTime == "" || this.form.startTime == null) {
        if (value == "0") {
          // 8小时
          this.calculateTime(endTime, "hour", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "1") {
          // 1天
          this.calculateTime(endTime, "day", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "2") {
          // 7天
          this.calculateTime(endTime, "day7", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "3") {
          // 14天
          this.calculateTime(endTime, "day14", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "4") {
          // 30天
          this.calculateTime(endTime, "day30", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else {
          // 60天
          this.calculateTime(endTime, "day60", "0");
          console.log(this.form.startTime, "this.form.startTime");
        }
      }
      // 当清空endtime 选择starttime和interval时
      if (this.form.endTime == "" || this.form.endTime == null) {
        // if (value == "0") {
        //     // 1小时
        //     this.calculateTime(this.form.startTime, "hour", "1");
        //     console.log(this.form.endTime, "this.form.endTime ");
        // } else if (value == "1") {
        //     // 1天
        //     this.calculateTime(this.form.startTime, "day", "1");
        //     console.log(this.form.endTime, "this.form.endTime ");
        // } else if (value == "2") {
        //     // 1周
        //     this.calculateTime(this.form.startTime, "week", "1");
        //     console.log(this.form.endTime, "this.form.endTime ");
        // } else {
        //     // 1月
        //     this.calculateTime(this.form.startTime, "month", "1");
        //     console.log(this.form.endTime, "this.form.endTime ");
        // }
        if (value == "0") {
          // 8小时
          this.calculateTime(this.form.startTime, "hour", "0");
          console.log(this.form.endTime, "this.form.endTime ");
        } else if (value == "1") {
          // 1天
          this.calculateTime(this.form.startTime, "day", "0");
          console.log(this.form.endTime, "this.form.endTime ");
        } else if (value == "2") {
          // 7天
          this.calculateTime(this.form.startTime, "day7", "0");
          console.log(this.form.endTime, "this.form.endTime ");
        } else if (value == "3") {
          // 14天
          this.calculateTime(this.form.startTime, "day14", "0");
          console.log(this.form.endTime, "this.form.endTime ");
        } else if (value == "4") {
          // 30天
          this.calculateTime(this.form.startTime, "day30", "0");
          console.log(this.form.endTime, "this.form.endTime ");
        } else {
          // 60天
          this.calculateTime(this.form.startTime, "day60", "0");
          console.log(this.form.endTime, "this.form.endTime ");
        }
      }
      // 当开始时间和结束时间都不为空时，根据结束时间和天数计算开始时间
      if (this.form.endTime !== "" && this.form.startTime !== "") {
        if (value == "0") {
          // 8小时
          this.calculateTime(endTime, "hour", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "1") {
          // 1天
          this.calculateTime(endTime, "day", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "2") {
          // 7天
          this.calculateTime(endTime, "day7", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "3") {
          // 14天
          this.calculateTime(endTime, "day14", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else if (value == "4") {
          // 30天
          this.calculateTime(endTime, "day30", "0");
          console.log(this.form.startTime, "this.form.startTime");
        } else {
          // 60天
          this.calculateTime(endTime, "day60", "0");
          console.log(this.form.startTime, "this.form.startTime");
        }
      }
    },
    calculateTime(timeString, unit, type) {
      const time = new Date(timeString);
      const step = {
        hour: 28800000, // 8小时
        day: 86400000, // 一天
        day7: 604800000, // 一天
        day14: 1209600000, // 一天
        day30: 2592000000, // 一天
        day60: 5184000000 // 一天
      };
      if (type == "0") {
        // 减 计算startTime
        const newTime = new Date(time.getTime() - step[unit]);
        this.form.startTime = this.formatDate(newTime);
      } else {
        // 加 计算endtime
        const newTime = new Date(time.getTime() + step[unit]);
        this.form.endTime = this.formatDate(newTime);
      }
    },
    // 将北京时间转换为卡尔加里时间
    convertBeijingToCalgary(beijingDate) {
      const options = {
          timeZone: 'America/Edmonton',  // 卡尔加里所属时区
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false                 // 强制24小时制
      };

      // 直接生成目标格式的字符串
      const formatter = new Intl.DateTimeFormat('en-CA', options);
      const calgaryTime = formatter.format(new Date())
          .replace(/(\d{4})-(\d{2})-(\d{2}),? (\d{2}:\d{2}:\d{2})/, '$1-$2-$3 $4');
          return calgaryTime
      // const now = new Date();
      // 获取UTC时间的毫秒数
      // const utcTime = now.getTime() + now.getTimezoneOffset() * 60000;
      // // 卡尔加里时间偏移量 (UTC-7)
      // const calgaryOffset = -7 * 60; // 以分钟为单位
      // // 计算卡尔加里时间
      // const calgaryTime = new Date(utcTime + calgaryOffset * 60000);
      // return calgaryTime;
      // const beijingOffset = 8 * 60; // 北京时间偏移量（分钟）
      // const calgaryOffset = -6 * 60; // 卡尔加里时间偏移量（分钟）
      // const offset = calgaryOffset - beijingOffset; // 时间差（分钟）
      // const calgaryDate = new Date(beijingDate.getTime() + offset * 60000);
      //return beijingDate;
    },
    // splitTimeIntoParts(startTime, endTime) {
    //     console.log(startTime, endTime, "startTime, endTime");
    //     const totalDuration = endTime - startTime;
    //     const partDuration = totalDuration / 10;
    //     this.splitTimes = [];

    //     for (let i = 0; i < 10; i++) {
    //         const newTime = this.formatDate(
    //             new Date(startTime.getTime() + partDuration * i)
    //         );
    //         this.splitTimes.push(newTime);
    //     }
    //     // this.splitTimes.push(endTime);
    // },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date
        .getDate()
        .toString()
        .padStart(2, "0");
      const hours = date
        .getHours()
        .toString()
        .padStart(2, "0");
      const minutes = date
        .getMinutes()
        .toString()
        .padStart(2, "0");
      const seconds = date
        .getSeconds()
        .toString()
        .padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    isDateObject(value) {
      return value instanceof Date;
    },
    clickCheck() {
      console.log(this.form);
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      this.getEachartsValue();
      // this.splitTimeIntoParts(
      //     new Date(this.form.startTime),
      //     new Date(endTime)
      // );
      // xAxis
      // this.option.xAxis[0].data = this.splitTimes;
      // this.option.xAxis[1].data = this.splitTimes;
      // console.log(this.option);
      // console.log(this.splitTimes, "this.splitTimes");
    },
    clickNext() {
      console.log(this.form, "form");
      if (
        this.form.startTime !== "" &&
        this.form.startTime !== null &&
        this.form.endTime !== "" &&
        this.form.endTime !== null
      ) {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        const time = new Date(endTime);
        const newTime = new Date(time.getTime() + 2592000000);
        this.form.startTime = this.form.endTime;
        this.form.endTime = this.formatDate(newTime);
      } else if (
        (this.form.startTime == "" || this.form.startTime == null) &&
        this.form.endTime !== "" &&
        this.form.endTime !== null
      ) {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        const time = new Date(endTime);
        const newTime = new Date(time.getTime() + 2592000000);
        this.form.startTime = this.form.endTime;
        this.form.endTime = this.formatDate(newTime);
      } else if (
        this.form.startTime !== "" &&
        this.form.startTime !== null &&
        (this.form.endTime == "" || this.form.endTime == null)
      ) {
        let startTime = "";
        if (this.isDateObject(this.form.startTime)) {
          startTime = this.formatDate(this.form.startTime);
        } else {
          startTime = this.form.startTime;
        }
        const time = new Date(startTime);
        const newTime = new Date(time.getTime() + 2592000000);
        this.form.startTime = this.formatDate(newTime);
      }
    },
    clickPrevious() {
      if (
        this.form.startTime !== "" &&
        this.form.startTime !== null &&
        this.form.endTime !== "" &&
        this.form.endTime !== null
      ) {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        const time = new Date(endTime);
        const newTime = new Date(time.getTime() - 2592000000);
        this.form.startTime = this.form.endTime;
        this.form.endTime = this.formatDate(newTime);
      } else if (
        (this.form.startTime == "" || this.form.startTime == null) &&
        this.form.endTime !== "" &&
        this.form.endTime !== null
      ) {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        const time = new Date(endTime);
        const newTime = new Date(time.getTime() - 2592000000);

        this.form.endTime = this.formatDate(newTime);
        const time2 = new Date(this.form.endTime);
        const newTime2 = new Date(time2.getTime() - 2592000000);
        this.form.startTime = this.formatDate(newTime2);
      } else if (
        this.form.startTime !== "" &&
        this.form.startTime !== null &&
        (this.form.endTime == "" || this.form.endTime == null)
      ) {
        let startTime = "";
        if (this.isDateObject(this.form.startTime)) {
          startTime = this.formatDate(this.form.startTime);
        } else {
          startTime = this.form.startTime;
        }
        const time = new Date(startTime);
        const newTime = new Date(time.getTime() - 2592000000);
        this.form.startTime = this.formatDate(newTime);
      }
    },
    // TODO使用mqtt 进行优化
    // initClient() {
    //     socket.methods.disconnect();
    //     if (!socket.methods.getClientState()) {
    //         let me = this;
    //         socket.methods.connection({
    //             location: "192.168.5.90",
    //             port: 31330,
    //             topics: "dwWell", // 井列表页面
    //             successMethod: me.successMethods,
    //             errorMethod: me.errorMethods,
    //         });
    //     }
    // },

    // 保留两位小数
    formattedArr(arr) {
      return arr.map(item => {
        return parseFloat(item).toFixed(2);
      });
    },

    // 获取折线图_产出管_温度(°C)
    async getESPTrend_WHT() {
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      // const parmas = {
      //     startTime: this.form.startTime,
      //     endTime: endTime,
      //     wellId: this.wellId,
      // };
      const res = await getESPTrend_WHT({
        startTime: this.form.startTime,
        endTime: endTime,
        wellId: this.wellId
      });
      console.log(res, "res");
      if (res.code === 200 && JSON.stringify(res.data) !== "{}") {
        this.xData = Object.keys(res.data.timeList).sort(function (a, b) {
          return new Date(a) - new Date(b);
        });
        const entries = Object.entries(res.data.timeList);
        entries.sort((a, b) => new Date(a[0]) - new Date(b[0]));
        const sortedData = Object.fromEntries(entries);
        console.log(sortedData, "aaa");
        const keys = Object.keys(sortedData);
        const values = Object.values(sortedData);
        this.xValue = values;
        this.xInterval = Math.ceil(keys.length / 10);
        this.option.xAxis[0].data = keys;
        this.option.xAxis[0].axisLabel.interval = this.xInterval;
        this.option.series[0].data = this.formattedArr(this.xValue);
        this.option.xAxis[1].data = keys;
        this.option.xAxis[1].axisLabel.interval = this.xInterval;
        this.init();
      }
    },
    // 获取tagName折线图
    async getTrendByTagType() {
      console.log("this.$route.query", this.$route.query);
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      const res = await getTrendByTagType({
        startTime: this.form.startTime,
        endTime: endTime,
        wellId: this.$route.query.wellId,
        tagType: this.tagType
      });
      console.log(res, "res");
      if (res.code === 200 && JSON.stringify(res.data) !== "{}") {
        // console.log(res, "res========");
        // this.xData = Object.keys(res.data.timeList).sort(function (
        //     a,
        //     b
        // ) {
        //     return new Date(a) - new Date(b);
        // });
        console.log(res.data.tagName, "pppppppppppppp2");
        this.$emit("sendData", res.data.tagName);
        const entries = Object.entries(res.data.timeList);
        entries.sort((a, b) => new Date(a[0]) - new Date(b[0]));
        const sortedData = Object.fromEntries(entries);
        console.log(sortedData, "aaa");
        const keys = Object.keys(sortedData);
        const values = Object.values(sortedData);
        this.xValue = values;
        this.xInterval = Math.ceil(keys.length / 10);
        this.option.xAxis[0].data = keys;
        this.option.xAxis[0].axisLabel.interval = this.xInterval;
        this.option.series[0].data = this.formattedArr(this.xValue);
        //this.option.legend[0].data[0] = `${this.tagName} ${this.unit}`;
        this.option.legend[0].data[0] = `${res.data.tagName}`;
        //this.option.series[0].name = `${this.tagName} ${this.unit}`;
        this.option.series[0].name = `${res.data.tagName}`;
        this.init();
      }
    },
    async getTrendByTagName() {
      let endTime = "";
      console.log(this.tagName, 'pppppppppppppp1')
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      const res = await getTrendByTagName({
        startTime: this.form.startTime,
        endTime: endTime,
        wellId: this.$route.query.wellId,
        tagName: this.tagName
      });
      console.log(res, "res");
      if (res.code === 200 && JSON.stringify(res.data) !== "{}") {
        this.$emit("sendData", res.data.tagName);
        this.xData = Object.keys(res.data.timeList).sort(function (a, b) {
          return new Date(a) - new Date(b);
        });
        const entries = Object.entries(res.data.timeList);
        entries.sort((a, b) => new Date(a[0]) - new Date(b[0]));
        const sortedData = Object.fromEntries(entries);
        console.log(sortedData, "aaa");
        const keys = Object.keys(sortedData);
        const values = Object.values(sortedData);
        this.xValue = values;
        this.xInterval = Math.ceil(keys.length / 10);
        this.option.xAxis[0].data = keys;
        this.option.xAxis[0].axisLabel.interval = this.xInterval;
        this.option.series[0].data = this.formattedArr(this.xValue);
        this.option.legend[0].data[0] = `${this.tagName} ${this.unit}`;
        this.option.series[0].name = `${this.tagName} ${this.unit}`;
        this.init();
      }
    },
    async getTrendByOnlyTagName() {
      let endTime = "";
      if (this.isDateObject(this.form.endTime)) {
        endTime = this.formatDate(this.form.endTime);
      } else {
        endTime = this.form.endTime;
      }
      const res = await getTrendOnlyByTagName({
        startTime: this.form.startTime,
        endTime: endTime,
        tagName: this.tagName
      });
      console.log(res, "res");
      if (res.code === 200 && JSON.stringify(res.data) !== "{}") {
        // console.log(res, "res========");
        // this.xData = Object.keys(res.data.timeList).sort(function (
        //     a,
        //     b
        // ) {
        //     return new Date(a) - new Date(b);
        // });
        this.$emit("sendData", res.data.tagName);
        const entries = Object.entries(res.data.timeList);
        entries.sort((a, b) => new Date(a[0]) - new Date(b[0]));
        const sortedData = Object.fromEntries(entries);
        console.log(sortedData, "aaa");
        const keys = Object.keys(sortedData);
        const values = Object.values(sortedData);
        this.xValue = values;
        this.xInterval = Math.ceil(keys.length / 10);
        this.option.xAxis[0].data = keys;
        this.option.xAxis[0].axisLabel.interval = this.xInterval;
        this.option.series[0].data = this.formattedArr(this.xValue);
        this.option.legend[0].data[0] = `${this.tagName} ${this.unit}`;
        this.option.series[0].name = `${this.tagName} ${this.unit}`;
        this.init();
      }
    },
    //点位导出
    async exportpointCheck() {
      this.exportdaochu = true;
      this.exportLoading = true;
      this.loading = true;
      if (this.keyType == '1') {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        let startTime = this.form.startTime;
        let wellId = this.$route.query.wellId;
        let tagType = this.tagType;
        try {
          const blob = await byTagType(wellId, startTime, endTime, tagType);
          exportFile(blob, 'Single Tag Trend', "xlsx");
        } catch (error) {
          console.error("Export failed:", error);
        } finally {
          this.exportdaochu = false;
          this.exportLoading = false;
          this.loading = false;
        }
      } else if (this.keyType == '2') {
        let endTime = "";
        if (this.isDateObject(this.form.endTime)) {
          endTime = this.formatDate(this.form.endTime);
        } else {
          endTime = this.form.endTime;
        }
        let startTime = this.form.startTime;
        let wellId = this.wellId;
        let tagName = this.tagName;
        try {
          const blob = await byTagName(wellId, startTime, endTime, tagName);
          exportFile(blob, 'Single Tag Trend', "xlsx");
        } catch (error) {
          console.error("Export failed:", error);
        } finally {
          this.exportdaochu = false;
          this.exportLoading = false;
          this.loading = false;
        }
      }
    },
    async getEachartsValue() {
      if (this.keyType === "2") {
        this.getTrendByTagName();
      } else if (this.keyType === "1") {
        this.getTrendByTagType();
      } else if (this.keyType === "4") {
        this.getTrendByOnlyTagName();
      }
      // try {
      //     // 并行调用所有接口
      //     const [
      //         whtData,
      //         tcdData,
      //         hzData,
      //         valveData,
      //         csgTempData,
      //         whpData,
      //         prdHeelData,
      //         stmHeelData,
      //         csgPresData,
      //         flowRateData,
      //         ampsData,
      //     ] = await Promise.all([
      //         this.getESPTrend_WHT(),
      //         this.getESPTrend_TCD(),
      //         this.getESPTrend_HZ(),
      //         this.getESPTrend_Valve(),
      //         this.getESPTrend_CsgTemp(),
      //         this.getESPTrend_WHP(),
      //         this.getESPTrend_PrdHeel(),
      //         this.getESPTrend_StmHeel(),
      //         this.getESPTrend_CsgPres(),
      //         this.getESPTrend_FlowRate(),
      //         this.getESPTrend_Amps(),
      //     ]);
      //     // 处理获取到的数据
      //     // ...
      // } catch (error) {
      //     console.error("An error occurred while fetching data:", error);
      // }
    }
  }
};
</script>



<style lang="scss" scoped>
:deep(.el-input__inner) {
  text-align: left !important;
}

.trendpad {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;

  .export_daochu {
    height: 83%;
    width: 90%;
    z-index: 2000;
    position: absolute;

    ::v-deep .el-loading-mask {
      background: rgba(0, 0, 0, 0.8);
    }
  }

  .content {
    width: 95%;
    height: 90%;
  }

  .footer {
    width: calc(100% - 1rem);
    padding: 0.7422rem 0;
    border-top: 1px solid #6f7072;
    border-bottom: 1px solid #6f7072;
    margin-top: 0.1484rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    z-index: 9999;

    .footer-item {
      color: #ffffff;
      width: 17.4961rem;

      .el-button {
        display: flex;
        margin-left: -14rem;
      }

      .el-input,
      .el-select {
        :deep(.el-input__inner) {
          background-color: #121a32;
          color: #000000;
          font-size: 0.6927rem;
          text-align: left !important;
        }
      }

      :deep(.el-select) {
        width: 9.3325rem;
        // height: 1.4844rem;
      }

      :deep(.el-input) {
        width: 14.3325rem !important;
        height: 2.4844rem !important;
        text-align: left;
      }

      :deep(.el-input.is-disabled .el-input__inner) {
        text-align: left;
      }

      :deep(.el-button) {
        color: #ffffff !important;
      }
    }
  }
}
</style>
